using System;
using System.Collections;
using System.Collections.Generic;
using Sirenix.OdinInspector;
using UnityEngine;

public class VActBehaviour : MonoBehaviour
{
    //有可能这个才是最顶级的入口
    //纯属性了+封装
    public VActProcessor processor;
    public VActMotionVectorMechine mechine;
    public Vector3 PlayerCamForward(float dis = 0) => player.position + player.forward * dis;
    private Transform player;

    public Dictionary<string, TriggerObserver> actions = new();
    private void Start()
    {
        processor = GetComponent<VActProcessor>();
        mechine = processor.mechine;
    }

    #region BehaviorCode
    public Transform apple;
    public VHTNBlock curRunningBlock;
    [Button]
    public void Fetch()
    {
        var htn = new VHTN();
        htn.Init();
        VHTN.Scope scope = new VHTN.Scope();

        scope.Set("Maseter", Camera.main);
        scope.Set("Order", "FetchObject");
        scope.Set("position", apple.position);
        scope.Set("Target", apple.gameObject);
        scope.Set("OriPos", transform.position);
        htn.Expense(htn.ToNode("FetchObject"), scope, this, new VHTNBlock());

        2f.Delay(() => scope.Set("Answer", "good"));
    }
    public Transform hand;
    private ContinueCache attachCache = new();
    public void Attach(GameObject attach)
    {
        //默认全attach到手上
        if (!ContinueCache.Update(attachCache, attach)) return;
        attach.transform.SetParent(hand);
        print("gameobject已设置在手上");
    }
    public void DeAttach(GameObject gameObject)
    {
        gameObject.transform.parent = null;
    }

    public bool SampleRandomPoint(out Vector3 pos) => processor.mechine.RandomSampleOnNavMesh(out pos);

    public float GetRotationToTarget(Vector3 targetPosition)
    {
        Vector3 toTarget = (targetPosition - transform.position).normalized;
        toTarget.y = 0;

        Vector3 forward = transform.forward.normalized;
        forward.y = 0;

        float angle = Vector3.Angle(forward, toTarget);
        Vector3 cross = Vector3.Cross(forward, toTarget);

        // 判断旋转方向并将角度归一化到-180到180度之间
        return cross.y > 0 ? angle : -angle;
    }
    #endregion

    public T GetParam<T>(string name) => (T)default;

    /// <summary>
    /// 个体会有具体的重载行为，通过这个映射表对行为重定向
    /// </summary>
    public Dictionary<string, string> behaviorOverride;

}


public class ContinueCache
{
    public int objectHash;
    public ContinueCache(int hash = 0) { objectHash = hash; }
    public static bool Update(ContinueCache cache, object obj)
    {
        if (cache.objectHash == obj.GetHashCode()) return false;
        cache.objectHash = obj.GetHashCode();
        return true;
    }
}